package hr.riteh.assistivecommunicator;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView;

public class ListChooserDialog extends AlertDialog implements AdapterView.OnItemClickListener
{
	private OnChosenListener mListener;
	private ListAdapter mAdapter;
	private ListView mListView;

	// Callback listener interface
	public interface OnChosenListener
	{
		void onChosen(int position);
	}

	public ListChooserDialog(Context context)
	{
		// Call constructor from superclass
		super(context);
	}

	public void setOnChosenListener(OnChosenListener listener)
	{
		// Save reference to callback listener
		mListener = listener;
	}

	public void setAdapter(ListAdapter adapter)
	{
		// Save reference to adapter
		mAdapter = adapter;

		// Set adapter to ListView also (if ListView exists)
		if (mListView != null)
		{
			mListView.setAdapter(adapter);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// Create ListView for displaying list of files
		mListView = new ListView(getContext());
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
		setView(mListView);

		// Configure dialog
		setCancelable(true);
		setCanceledOnTouchOutside(true);

		// Method onCreate() of the superclass must be called after the dialog has been configured
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id)
	{
		// Call callback listener (if set)
		if (mListener != null)
		{
			mListener.onChosen(position);
		}

		// Dismiss (close) dialog
		dismiss();
	}
}
